package com.itheima.reggie.controller;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/page",name = "分页查询")
    public ResultInfo pageList(@RequestParam(value = "page",defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer pageSize, String name){
        Page<Dish> page = dishService.pageList(pageNum,pageSize,name);
        return ResultInfo.success(page);
    }


    @PostMapping(name = "添加菜品")
    public ResultInfo save(@RequestBody Dish dish){
        //清除huanc
        redisTemplate.delete("dish:"+dish.getCategoryId());
        dishService.dishSave(dish);
        return ResultInfo.success(null);
    }

    @GetMapping(value = "/{id}",name = "根据id查询菜品信息")
    public ResultInfo findById(@PathVariable("id") Long id){
        Dish dish =  dishService.findById(id);
        return ResultInfo.success(dish);
    }


    @PutMapping(name = "菜品更新")
    public ResultInfo  update(@RequestBody Dish dish){
        //清除huanc
        redisTemplate.delete("dish:"+dish.getCategoryId());
        dishService.update(dish);
        return ResultInfo.success(null);
    }


    @DeleteMapping(name = "菜品的批量删除")
    public ResultInfo deletes(Long[] ids){
        //清除缓存
        Set keys = redisTemplate.keys("dish:" + "*");
        redisTemplate.delete(keys);
        String messAge  =  dishService.deletes(ids);
        if (StringUtils.isNotEmpty(messAge)){
            throw new CustomException(messAge+",批量删除失败");
        }
        return ResultInfo.success(null);
    }


    @PostMapping(value = "/status/{status}",name = "修改销售状态")
    public ResultInfo statusUpdate(@PathVariable("status") Integer status,Long[] ids){
        Set keys = redisTemplate.keys("dish:" + "*");
        //清除缓存
        redisTemplate.delete(keys);
        dishService.statusUpdate(status,ids);
        return ResultInfo.success(null);
    }


    @GetMapping(value = "/list",name = "套餐的菜品信息回显")
    public ResultInfo findByIdNamelike(Long categoryId,String name){
        List<Dish> dishList = dishService.findByIdNamelike(categoryId,name);
        return ResultInfo.success(dishList);
    }
}
